package com.runvp.service.biz.service;

import com.runvp.common.build.BuildAppUtil;
import com.runvp.common.build.model.DownloadListKey;
import com.runvp.common.build.model.DownloadListModel;
import com.runvp.common.utils.ShiroUtils;
import com.runvp.common.utils.StringUtils;
import com.runvp.system.mapper.SysDictDataMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 首创 html调用 thymeleaf 实现下拉列表读取
 *
 * @author update for xkk
 */
@Service("udwl")
public class DllService {

    @Autowired
    private SysDictDataMapper dictDataMapper;

    /**
     * 根据业务类型获取下拉列表
     *
     * @param tableName
     * @return list
     */
    public List<DownloadListModel> getTableData(String tableName,String idKey,String nameKey,String status) {
        String customCondition = "";
        if(!ShiroUtils.getSysUser().isAdmin()){
            customCondition = " AND tenant_id = "+ShiroUtils.bizUserId();
        }
        DownloadListKey key = new DownloadListKey(tableName,idKey,nameKey, status);
        key.setCustomConditionExecute(customCondition+" order by create_time desc ");
        List<DownloadListModel> modelList = dictDataMapper.getListByTable(key);
        if (CollectionUtils.isEmpty(modelList)) {
            return new ArrayList<>();
        }
        for(DownloadListModel model:modelList){
            if(StringUtils.isEmpty(model.getDictLabel())){
                model.setDictLabel(model.getDictValue());
            }else {
                model.setDictLabel(model.getDictLabel()+"(ID:"+model.getDictValue()+")");
            }
        }
        return modelList;
    }

    /**
     * 根据业务类型获取下拉列表
     *
     * @param dictType
     * @return list
     */
    public List<DownloadListModel> getType(String dictType, String... customConditionValue) {
        DownloadListKey key = BuildAppUtil.getByType(dictType);
        String customCondition = key.getCustomCondition();
        if (StringUtils.isNotEmpty(customCondition)) {
            String cv = "";
            for (int i = 0; i < customConditionValue.length; i++) {
                //根据登录用户查询
                if ("my".equals(customConditionValue[i])) {
                    cv = ShiroUtils.bizUserIdStr();
                } else {
                    cv = customConditionValue[i];
                }
                customCondition = customCondition.replace("{{condition" + i + "}}", cv);
            }
        }
        key.setCustomConditionExecute(customCondition);
        List<DownloadListModel> modelList = dictDataMapper.getListByTable(key);
        if (CollectionUtils.isEmpty(modelList)) {
            return new ArrayList<>();
        }
        return modelList;
    }
}
